package com.hm.health.Activity.ecg;

import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.pdf.PdfDocument;
import android.os.Environment;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;

import com.goodix.activity.FileBrowserActivity;
import com.goodix.utils.SPUtils;
import com.goodix.utils.TimeUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hm.health.Activity.BaseActivity;
import com.hm.health.R;
import com.hm.health.View.ECGChartView;
import com.hm.health.entity.dao.EcgStatistics;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


public class ExportEcgToPdfActivity extends BaseActivity {

    public static final String TAG = "ExportEcgToPdfActivity";

    private static final int REQUEST_CODE = 1;

    @BindView(R.id.rl_pdf_view)
    RelativeLayout mRlPdfView;
    private EcgStatistics mStatistics;
    @BindView(R.id.ecg_view_1)
    ECGChartView mECGChartView1;
    @BindView(R.id.ecg_view_2)
    ECGChartView mECGChartView2;
    @BindView(R.id.ecg_view_3)
    ECGChartView mECGChartView3;
    @BindView(R.id.tv_record_time)
    TextView mTvRecordTime;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_hr_average)
    TextView mTvHrAverage;
    @BindView(R.id.tv_pathological_information)
    TextView mTvPathologicalInformation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_export_ecg_to_pdf);
        ButterKnife.bind(this);

        initActionBar(getString(R.string.export_ecg_chart));
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        String jsonStr = getIntent().getStringExtra(EcgHistoryDetailActivity.EXT_ECG_HISTORY_DETAIL_INFO);
        if (null != jsonStr) {
            mStatistics = new Gson().fromJson(jsonStr, new TypeToken<EcgStatistics>(){}.getType());
        }

        loadEcgData();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == REQUEST_CODE) {
            String path = data.getStringExtra(FileBrowserActivity.EXTRA_KEY_PATH);
            String time = TimeUtil.formateTime(System.currentTimeMillis());
            saveViewToPDF(mRlPdfView, path, String.format("ecg-chart-%s.pdf", time));
            finish();
        }
    }


    private void loadEcgData() {

        mTvRecordTime.setText(mStatistics.getStartTime());
        mTvName.setText(mStatistics.getTesterName());

        // 心率均值
        mTvHrAverage.setText(String.format(getString(R.string.hr_average_format), mStatistics.getHrAverage()));

        // 节律信息
        String[] pathological = getResources().getStringArray(R.array.pathological);
        int type = mStatistics.getPathologicalInformation();
        if (type < pathological.length) {
            mTvPathologicalInformation.setText(pathological[type]);
        } else {
            mTvPathologicalInformation.setText(pathological[0]);
        }

        String filePath = mStatistics.getEcgRawdataPath();
        ArrayList<Integer> datas = SPUtils.getJsonObj(mContext, filePath, new ArrayList<>(),
                new TypeToken<List<Integer>>(){}.getType());

        int freq = mStatistics.getFrequence();

        mECGChartView1.setFrequency(10, freq);
        mECGChartView1.setLineWidth(1);
        mECGChartView2.setFrequency(10, freq);
        mECGChartView2.setLineWidth(1);
        mECGChartView3.setFrequency(10, freq);
        mECGChartView3.setLineWidth(1);

        for (int i = 0; i < freq * 30; ++i) {
            float v = ECGChartView.INVALID_ECG;
            if (i < datas.size()) {
                v = datas.get(i) / 100f;
            }

            if (i < freq * 10) {
                mECGChartView1.addPoint(v, i + 1);
            } else if (i >= freq * 10 && i < freq * 20) {
                mECGChartView2.addPoint(v, i + 1);
            } else if (i >= freq * 20) {
                mECGChartView3.addPoint(v, i + 1);
            }
        }

        mECGChartView1.invalidate();
        mECGChartView2.invalidate();
        mECGChartView3.invalidate();
    }

    protected void initActionBar(String title) {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        setCenterTitle(title);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.ecg_save, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.ecg_save:
                String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                FileBrowserActivity.startBrowser(ExportEcgToPdfActivity.this,
                        REQUEST_CODE, true, "", path);
                break;
            case R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void saveViewToPDF(View view, String savePath, String name){
        // create a new document
        PdfDocument document = new PdfDocument();

        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
                view.getWidth(), view.getHeight(), 1).create();

        // start a page
        PdfDocument.Page page = document.startPage(pageInfo);

        // draw something on the page
        Canvas canvas = page.getCanvas();
        view.draw(canvas);

        // finish the page
        document.finishPage(page);

        File file = new File(savePath, name);
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            document.writeTo(outputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            document.close();
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
